package com.smilive.start.netty.jdk;

import com.google.common.collect.Lists;
import com.smilive.start.netty.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 * @program: netty_start
 * @Date: 2022-01-04 14:27
 * @Author: smilive
 * @Description: 非阻塞
 */
@Slf4j
public class NetServerNoBlocking {

    public static void main(String[] args) {
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        // 获得服务器通道
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()){
            serverSocketChannel.bind(new InetSocketAddress(8000));
            ArrayList<SocketChannel> channels = Lists.newArrayList();
            while (true){
                // 设置为非阻塞模式，没有连接时返回null，不会阻塞线程
                serverSocketChannel.configureBlocking(false);
                SocketChannel socketChannel = serverSocketChannel.accept();
                // 通道不为空时才将连接放入到集合中
                if (socketChannel != null){
                    log.debug("连接接入:{}",socketChannel);
                    channels.add(socketChannel);
                }
                for (SocketChannel channel : channels) {
                    // 处理通道中的数据
                    // 设置为非阻塞模式，若通道中没有数据，会返回0，不会阻塞线程
                    channel.configureBlocking(false);
                    int read = channel.read(byteBuffer);
                    if (read > 0){
                        byteBuffer.flip();
                        ByteBufferUtil.debugAll(byteBuffer);
                        byteBuffer.clear();
                        log.debug("接收数据完毕");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
